%% Euler's method for solving an ODE
%
% Euler's method 

g=.5;
dt=.1
t0=0;
t=(t0:dt:10)'%Note I'm making t a column vector

%This is an intial value problem with 'x' at t=0 given by:
x0=1

%We know the analytical solution must then be
A=x0;
x_analytical=@(t) A*exp(-g*t);  %Create anonymous function

% Create anonymous function
x_p=@(x_current) -g*x_current

%Intialize empty results vector
x_found=zeros(length(t),1)

%Set first point to our initial value
x_found(1)=x0


%Run Euler's method
for ii=1:length(t)-1
   x_cur=x_found(ii);   
   x_found(ii+1)= x_cur+dt*x_p(x_cur);
end

%Plot results
figure
plot(t,x_found)
xlabel('time')
ylabel('x')

%compare to known analytical result
x_found_analytical=x_analytical(t)
hold on
plot(t,x_found_analytical)
legend('Euler Method','Analytical')

%Try changing 'dt' and comparing results. 

%Plot residual
residual=x_found-x_found_analytical;
figure
plot(t,residual)
xlabel('time')
ylabel('x')
legend('Found - Known')
title('Residual')



















